from py2neo import Graph, Node, Relationship
from config import Config
import json


class dataToNeo4j():
    def __init__(self):
        self.neo4j_graph = Graph(Config.GRAPH_HOST, user=Config.GRAPH_USER, password=Config.GRAPH_PASSWD)

    def create_relation_ship(self, start_node, end_node, edges, rel_name):
        """
        创建实体关系边
        :param start_node:
        :param end_node:
        :param edges:
        :param rel_name:
        :return:
        """
        try:
            count = 0
            # 去重处理
            set_edges = []
            for edge in edges:
                set_edges.append('###'.join(edge))
            # print(set_edges)
            all = len(set(set_edges))
            for edge in set(set_edges):
                edge = edge.split('###')
                p = edge[0]
                q = edge[1]
                query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s]->(q)" % (
                    start_node, end_node, p, q, rel_name)
                # print(query)
                try:
                    self.neo4j_graph.run(query)
                    count += 1
                    print(count, all)
                except Exception as e:
                    print(e)
                    # print(rel_name + "的数量是 %d " % (count))
        except Exception  as e:
            print(e)
            pass
        return

    def query_node(self, label, name):
        """
        查询节点是否存在
        :param label: 节点label
        :param name: 节点名字
        :return: 0不存在，1存在
        """
        sql = 'Match (n:%s) where n.name = "%s" return n' % (label, name)
        result = self.neo4j_graph.run(sql).data()
        if len(result) == 0:
            return 0
        else:
            return 1

    def create_node(self, label, name):
        """
        创建节点
        :param label: 节点标签
        :param nodes: 节点
        :return: 
        """
        node = Node(label, name=name)
        self.neo4j_graph.create(node)

    def relat_exists(self, label, node1, node2, relat):
        """"
        判断关系是否存在
        """
        query = "match p=(:%s{name:'%s'})-[]-(m) where m.name='%s' return p" % (label, node1, node2)
        try:
            result = self.neo4j_graph.run(query).data()
            rel = []
            for i in result:
                for j in i['p'].relationships:
                    rel.append(type(j).__name__)
        except Exception as e:
            result = []
            print(e)
        if len(result) != 0 and relat in rel:
            return False
        else:
            return True
    def deleate_(self):
        sql='match (n1:`对口就业行业`),(n2:`行业细分类`) optional match (n1)-[r]-(n2) LIMIT 25 delete r '
        result = self.neo4j_graph.run(sql).data()

    def createRelationShip_contant(self, start_node, end_node, edges, rel_type, main_disease, rel_name={}):
        """
        创建实体关系边
        :param start_node:
        :param end_node:
        :param edges:
        :param rel_type:
        :param rel_name:
        :return:
        """
        # print(f'====开始{rel_type}关系导入')
        count = 0
        p = edges[0]
        q = edges[1]
        if self.relat_exists(start_node, p, q, rel_type):
            if p == q:
                return
            query = "match(p:%s),(q:%s) where p.name='%s'and q.name='%s' create (p)-[rel:%s{%s:'%s'}]->(q)" % (
                start_node, end_node, p, q, rel_type, main_disease, rel_name)
            print(query)
            try:
                self.neo4j_graph.run(query)
                count += 1
                # print(rel_type, count, all)
            except Exception as e:
                print(e)
        # print(rel_type + "的全部数量是 %d " % (count))
        return
# dataToNeo4j().createRelationShip_contant("高考专业","对口就业行业",["麻醉学","医疗机构"],"傻逼","麻醉学")
# dataToNeo4j().deleate_()
# match (n1:),(n2)
# where n1.name="血清降钙素" AND n2.name="颈部"
# optional match (n1)-[r]-(n2)
# delete r
# match (n1:`疾病症状`),(n2:`疾病症状`) optional match (n1)-[r]-(n2) delete r
# match (n1:`高考专业`),(n2:`对口就业行业`)  where n1.name="麻醉学" AND n2.name="医疗机构" optional match p=(n1)-[r]-(n2) SET r={title:"尾部"} return p
# match (n1:`高考专业`),(n2:`对口就业行业`)  where n1.name="麻醉学" AND n2.name="医疗机构" optional match (n1)-[r]-(n2) SET r={title:"尾部"} RETURN p